package com.metronoteapp.database;

import com.metronoteapp.model.GroupModel;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

	public static final String TAG = DBHelper.class.getSimpleName();
	public static final String DB_NAME = "MetroNote.db";
	public static final int DB_VERSION = 1;
	public static final String DROP_TABLE = "DROP TABLE IF EXISTS";
	public static final String[] CREATE_TABLES = { UserDao.CREATE_TABLE,
												   GroupNoteDao.CREATE_TABLE,
												   NoteDao.CREATE_TABLE};
	public static final String[] DROP_TABLES = { UserDao.TABLE_NAME,
												 GroupNoteDao.TABLE_NAME,
												 NoteDao.TABLE_NAME};

	public DBHelper(Context _context) {
		super(_context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase _db) {
		Log.v(TAG, "onCreate() | Create Table User | " + UserDao.CREATE_TABLE);
		Log.v(TAG, "onCreate() | Create Table Group Note | " + GroupNoteDao.CREATE_TABLE);
		Log.v(TAG, "onCreate() | Create Table Note | " + NoteDao.CREATE_TABLE);
		_db.beginTransaction();
		try {
			for (String table : CREATE_TABLES) {
				Log.v(TAG, "table=" + table);
				_db.execSQL(table);
			}
			_db.setTransactionSuccessful();
		} catch (SQLException ex) {
			ex.printStackTrace();
		} finally {
			_db.endTransaction();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {
			Log.v(TAG, "Updating database...");
			for (String table : DROP_TABLES) {
				db.execSQL(DROP_TABLE + table);
			}
			onCreate(db);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}